#!/usr/bin/env python3
"""
simulate_attacks.py
Generates a set of attack scripts that run in an isolated VM. These scripts aim to create
observable OS behaviors: fork bombs (high process churn), ransomware-like bulk file writes,
command injection, and simple lateral movement (ssh) simulation.

USAGE: run individual functions only inside an isolated VM. Do NOT run on production.
"""
import os
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument('--attack', choices=['forkbomb','ransom','slow-breach','scan'], required=True)
args = parser.parse_args()

if args.attack == 'forkbomb':
    # create lots of short-lived processes to stress the process monitor
    for i in range(1000):
        pid = os.fork()
        if pid == 0:
            # child
            os.execvp('bash', ['bash', '-c', 'sleep 0.01; exit'])
        else:
            time.sleep(0.005)

if args.attack == 'ransom':
    # Encrypt files in a test directory using openssl
    testdir = '/tmp/testfiles_ransom'
    os.makedirs(testdir, exist_ok=True)
    # create many files
    for i in range(200):
        fname = os.path.join(testdir, f'f{i}.txt')
        with open(fname, 'w') as f:
            f.write('A'*10000)
    # encrypt
    for fpath in os.listdir(testdir):
        full = os.path.join(testdir, fpath)
        out = full + '.enc'
        # call openssl (installed in VM)
        os.system(f"openssl enc -aes-256-cbc -pbkdf2 -salt -in '{full}' -out '{out}' -k password")
        time.sleep(0.01)

if args.attack == 'slow-breach':
    # create a stealthy process that slowly spawns children at long intervals to simulate slow attack
    for i in range(50):
        os.system('sleep 2; touch /tmp/slow_attack_{}'.format(i))
        time.sleep(5)

if args.attack == 'scan':
    # run nmap -sS on local network (ensure isolated lab)
    os.system('nmap -sS 192.168.1.0/24 -oN /tmp/nmap_scan.txt')